package com.harmontronics.hanma.paas.paas.domain.hmureport.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.harmontronics.hanma.paas.paas.common.PageBase;
import com.harmontronics.hanma.paas.paas.domain.hmureport.entity.HmUreportFile;
import com.harmontronics.hanma.paas.paas.domain.hmureport.entity.valueobject.HmUreportFileFields;
import com.harmontronics.hanma.paas.paas.domain.hmureport.entity.valueobject.I18nKeyEnum;
import com.harmontronics.hanma.paas.paas.domain.hmureport.repository.persistence.HmUreportFileRepository;
import com.harmontronics.hanma.paas.paas.domain.hmureport.repository.po.HmUreportFilePO;
import com.harmontronics.hanma.paas.paas.exception.ErrorKeyException;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;

@Service("hmUreportFileService")
@DS("#header.App-Unique")
public class HmUreportFileService {

    @Autowired
    private HmUreportFileRepository hmUreportFileRepository;

    private String prefix = "postgres:";

    private String preFile = ".ureport.xml";

    private static final String fileContent =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ureport><cell expand=\"None\" name=\"A1\" row=\"1\" col=\"1\"><cell-style font-size=\"10\" align=\"center\" valign=\"middle\"></cell-style><simple-value><![CDATA[]]></simple-value></cell><cell expand=\"None\" name=\"B1\" row=\"1\" col=\"2\"><cell-style font-size=\"10\" align=\"center\" valign=\"middle\"></cell-style><simple-value><![CDATA[]]></simple-value></cell><cell expand=\"None\" name=\"C1\" row=\"1\" col=\"3\"><cell-style font-size=\"10\" align=\"center\" valign=\"middle\"></cell-style><simple-value><![CDATA[]]></simple-value></cell><cell expand=\"None\" name=\"D1\" row=\"1\" col=\"4\"><cell-style font-size=\"10\" align=\"center\" valign=\"middle\"></cell-style><simple-value><![CDATA[]]></simple-value></cell><cell expand=\"None\" name=\"A2\" row=\"2\" col=\"1\"><cell-style font-size=\"10\" align=\"center\" valign=\"middle\"></cell-style><simple-value><![CDATA[]]></simple-value></cell><cell expand=\"None\" name=\"B2\" row=\"2\" col=\"2\"><cell-style font-size=\"10\" align=\"center\" valign=\"middle\"></cell-style><simple-value><![CDATA[]]></simple-value></cell><cell expand=\"None\" name=\"C2\" row=\"2\" col=\"3\"><cell-style font-size=\"10\" align=\"center\" valign=\"middle\"></cell-style><simple-value><![CDATA[]]></simple-value></cell><cell expand=\"None\" name=\"D2\" row=\"2\" col=\"4\"><cell-style font-size=\"10\" align=\"center\" valign=\"middle\"></cell-style><simple-value><![CDATA[]]></simple-value></cell><cell expand=\"None\" name=\"A3\" row=\"3\" col=\"1\"><cell-style font-size=\"10\" align=\"center\" valign=\"middle\"></cell-style><simple-value><![CDATA[]]></simple-value></cell><cell expand=\"None\" name=\"B3\" row=\"3\" col=\"2\"><cell-style font-size=\"10\" align=\"center\" valign=\"middle\"></cell-style><simple-value><![CDATA[]]></simple-value></cell><cell expand=\"None\" name=\"C3\" row=\"3\" col=\"3\"><cell-style font-size=\"10\" align=\"center\" valign=\"middle\"></cell-style><simple-value><![CDATA[]]></simple-value></cell><cell expand=\"None\" name=\"D3\" row=\"3\" col=\"4\"><cell-style font-size=\"10\" align=\"center\" valign=\"middle\"></cell-style><simple-value><![CDATA[]]></simple-value></cell><row row-number=\"1\" height=\"18\"/><row row-number=\"2\" height=\"18\"/><row row-number=\"3\" height=\"18\"/><column col-number=\"1\" width=\"80\"/><column col-number=\"2\" width=\"80\"/><column col-number=\"3\" width=\"80\"/><column col-number=\"4\" width=\"80\"/><paper type=\"A4\" left-margin=\"90\" right-margin=\"90\"\n"
                    + "    top-margin=\"72\" bottom-margin=\"72\" paging-mode=\"fitpage\" fixrows=\"0\"\n"
                    + "    width=\"595\" height=\"842\" orientation=\"portrait\" html-report-align=\"left\" bg-image=\"\" html-interval-refresh-value=\"0\" column-enabled=\"false\"></paper></ureport>";

    public HmUreportFile findById(Long id) {
        HmUreportFilePO po = hmUreportFileRepository.getById(id);
        return BeanUtil.toBean(po, HmUreportFile.class);
    }

    public String save(HmUreportFile hmUreportFile) {
        HmUreportFilePO po = BeanUtil.toBean(hmUreportFile, HmUreportFilePO.class);
        String fileName = po.getFileName() + preFile;
        validateFileName(fileName);
        po.setFileName(fileName);
        po.setFileContent(fileContent.getBytes());
        hmUreportFileRepository.save(po);
        return prefix + fileName;

    }

    public void saveForReport(HmUreportFile hmUreportFile) {
        HmUreportFilePO po = BeanUtil.toBean(hmUreportFile, HmUreportFilePO.class);
        hmUreportFileRepository.save(po);
    }

    public void update(HmUreportFile hmUreportFile) {
        HmUreportFilePO po = hmUreportFileRepository.getById(hmUreportFile.getId());
        if (Optional.ofNullable(po).isPresent()) {
            po.setReportDesc(hmUreportFile.getReportDesc());
            hmUreportFileRepository.updateById(po);
        }
    }

    public void updateForReport(HmUreportFile hmUreportFile) {
        HmUreportFilePO po = BeanUtil.toBean(hmUreportFile, HmUreportFilePO.class);
        hmUreportFileRepository.updateById(po);

    }

    public void remove(List<Long> ids) {
        hmUreportFileRepository.removeByIds(ids);
    }

    public List<HmUreportFile> getList() {
        List<HmUreportFilePO> pos = hmUreportFileRepository.list();
        return Convert.toList(HmUreportFile.class, pos);
    }

    public PageBase<HmUreportFile> getList(int pageNo, int pageSize, String fileName) {

        Page<HmUreportFilePO> page = new Page<>(pageNo, pageSize);
        QueryWrapper<HmUreportFilePO> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(fileName)) {
            queryWrapper.like(HmUreportFileFields.FILE_NAME, fileName);
        }
        IPage<HmUreportFilePO> resultPage =
                hmUreportFileRepository.selectPage(queryWrapper, page);
        List<HmUreportFilePO> list = resultPage.getRecords();
        list.forEach(po -> {
            String tmpName = po.getFileName();
            po.setFileName(prefix + tmpName);
            po.setPreFileName(tmpName.substring(0, tmpName.indexOf(".")));
            po.setFileContent("".getBytes(StandardCharsets.UTF_8));
        });
        return PageBase.from(resultPage, HmUreportFile.class);
    }

    public HmUreportFile queryUreportFileEntityByName(String fileName) {
        QueryWrapper<HmUreportFilePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(HmUreportFileFields.FILE_NAME, fileName);
        HmUreportFilePO hmUreportFilePO = hmUreportFileRepository.getOne(queryWrapper);
        return BeanUtil.toBean(hmUreportFilePO, HmUreportFile.class);
    }

    public void deleteReportFileByName(String fileName) {
        QueryWrapper<HmUreportFilePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(HmUreportFileFields.FILE_NAME, fileName);
        hmUreportFileRepository.remove(queryWrapper);
    }

    private void validateFileName(String fileName) {
        QueryWrapper<HmUreportFilePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(HmUreportFileFields.FILE_NAME, fileName);
        List<HmUreportFilePO> list = hmUreportFileRepository.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            throw new ErrorKeyException(I18nKeyEnum.REPORT_FILENAME_EXIST);
        }

    }

}